package com.wangjw.tuling.nio.channels;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * Created by wangjianwen on 2018/12/5.
 */
public class CopyFile {

    public static void main(String[] args) throws IOException{
        String inFile = "temp/name.txt";
        String outFile = "temp/out_name.txt";

        // 从流中获取通道
        FileInputStream in = new FileInputStream(inFile);
        FileOutputStream out = new FileOutputStream(outFile);
        FileChannel inChannel = in.getChannel();
        FileChannel outChannel = out.getChannel();

        // 创建缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        while (true) {
            // 读之前要清空
            buffer.clear();

            // position 自动前进
            int r = inChannel.read(buffer);
            if (r == -1) {
                break;
            }

            // position = 0, limit = 读到的字节数
            buffer.flip();

            // 从 buffer 中读
            outChannel.write(buffer);
        }
    }
}
